<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>拖拽盒子</title>
    <style>
      /* 盒子样式 */
      #draggable {
        width: 150px;
        height: 150px;
        background-color: #4caf50;
        color: white;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        position: absolute;
        /* 防止鼠标选中元素 */
        user-select: none;
      }
    </style>
  </head>
  <body>
    <div class="tip">点击拖拽盒子</div>
    <div id="draggable">拖拽我</div>

    <script>
      // 获取拖拽盒子
      const draggable = document.getElementById('draggable')
      const tip = document.querySelector('.tip')

      // 定义初始位置
      let offsetX,
        offsetY,
        isDragging = false

      // 鼠标按下事件
      draggable.addEventListener('mousedown', e => {
        tip.innerHTML = '正在拖拽'
        isDragging = true
        // 获取鼠标相对盒子的位置
        offsetX = e.clientX - draggable.offsetLeft
        offsetY = e.clientY - draggable.offsetTop
        draggable.style.cursor = 'grabbing'
      })

      // 鼠标移动事件
      document.addEventListener('mousemove', e => {
        if (isDragging) {
          // 更新盒子的位置
          draggable.style.left = `${e.clientX - offsetX}px`
          draggable.style.top = `${e.clientY - offsetY}px`
        }
      })

      // 鼠标松开事件
      document.addEventListener('mouseup', () => {
        tip.innerHTML = '点击拖拽盒子'
        isDragging = false
        draggable.style.cursor = 'pointer'
      })
    </script>
  </body>
</html>
